import axios from 'axios'
import {Message} from 'element-ui'

import store from '../store'

import {getToken} from '@/request/token'
import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex);


/**
 * 创建一个客户端实例，而非每次都走axios
 * withCredentials:true =>跨域请求，允许保存cookie
 * timeout=>请求超时时间
 * @type {AxiosInstance}
 */
const service = axios.create({
  baseURL: process.env.BASE_URL,
  withCredentials: true,
  timeout: 15000,
});
/**
 * 请求拦截
 */
service.interceptors.request.use(config => {
  if (getToken()) {
    config.headers['Oauth-Token'] = getToken()
  }
  return config
}, error => {
  return Promise.reject(error)
});
/**
 * 响应拦截
 */
service.interceptors.response.use(res => {
    if (res.headers['session_time_out'] == 'timeout') {
      //退出
      store.dispatch('fedLogOut')
    }
    const r = res.data;
//0 为成功状态
    if (r.code !== 0) {
      if (r.code === 90001) {
        //超时
        return Promise.reject('error');
      }
      //20001 用户未登录
      if (r.code === 20001) {
        console.info("用户未登录");

        Message({
          type: 'warning',
          showClose: true,
          message: '未登录或登录超时，请重新登录哦'
        });
        return Promise.reject('error');
      }

      //70001 权限认证错误
      if (r.code === 70001) {
        console.info("权限认证错误")
        Message({
          type: 'warning',
          showClose: true,
          message: '你没有权限访问哦'
        });
        return Promise.reject('error');
      }
      return Promise.reject(r.msg);
    } else {
      return r;
    }
  },
  error => {
    Message({
      type: 'warning',
      showClose: true,
      message: '连接超时'
    });
    return Promise.reject('error')
  });

export default service
